import axios from 'axios';
import { Message } from '@arco-design/web-vue';
import { useStore } from '@/stores';
import settings from '@/constants/settings';

const request = axios.create({
    baseURL: settings.api.baseUrl,
    timeout: 10000
});

request.interceptors.request.use(
    (config) => {
        const token = useStore().auth?.access_token;
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
        config.headers['X-Application-Token'] = settings.api.applicationToken;
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

request.interceptors.response.use(
    (response) => {
        const res = response.data;
        
        if (res.code === 200) {
            return response;
        }
        
        if (res.code === 1003) {
            window.location.href = '/signin';
            return Promise.reject(new Error('Login required'));
        }

        if (res.code === 9202 || res.code === 4000) {
            return response;
        }
        
        Message.error(res.text || 'Request failed');
        return Promise.reject(new Error(res.text || 'Request failed'));
    },
    (error) => {
        Message.error(error.message || 'Request failed');
        return Promise.reject(error);
    }
);

export default request; 